const { createApp, reactive, computed, watch, ref, toRefs, onMounted } = Vue;

const app = createApp({
  setup() {
    const data = reactive({
      cardName: "",
      cardNumber: "",
      cardMonth: "",
      cardYear: "",
      cardCvv: "",
      minCardYear: new Date().getFullYear(),
      otherCardMask: "#### #### #### ####",
      isCardFlipped: false,
      focusElementStyle: null,
      isInputFocused: false,
    });
    // 目标 3 TODO Start：补充计算属性 minCardMonth 及 cardYear 的 watch 监听，最终实现本年只能选择当前月份及以后的月份。即，当页面中选中的 Year 下拉框为当前年份时，minCardMonth 的值只能为包含当前月份及其之后的月份。例如：当前年月为 2023 年 7 月，且 Year 下拉框选中的为 2023（即 minCardYear 为 2023），则只能选 7～12月。
    const minCardMonth = computed(() => {
      // return 1;
      if (data.cardYear == data.minCardYear) return new Date().getMonth() + 1;
      else return 1;
    });
    watch(
      () => {
        // 比如今年是2025年，最小月份是3月，我先选择了2026年的1月，然后切换到2025年，那么月份就要重新选了
        if (data.cardMonth < minCardMonth.value) {
          data.cardMonth = "";
        }
        return data.cardYear.value; // 返回想要监听的响应式数据，ref 定义的数据需要返回其 value 属性
      },
      () => {
        console.log("data.cardYear 发生了变化");
      },
      {
        immediate: true,
      }
    );
    // 目标 3 TODO End
    const cardNumberRef = ref(null);
    const cardNameRef = ref(null);
    const cardDateRef = ref(null);
    const flipCard = (status) => {
      data.isCardFlipped = status;
    };
    const focusInput = (e) => {
      data.isInputFocused = true;
      let targetRef = e.target.dataset.ref;

      let target = null;
      switch (targetRef) {
        case "cardNumberRef":
          target = cardNumberRef.value;
          break;
        case "cardNameRef":
          target = cardNameRef.value;
          break;
        case "cardDateRef":
          target = cardDateRef.value;
          break;
      }
      if (target) {
        data.focusElementStyle = {
          width: `${target.offsetWidth}px`,
          height: `${target.offsetHeight}px`,
          transform: `translateX(${target.offsetLeft}px) translateY(${target.offsetTop}px)`,
        };
      }
    };
    const blurInput = () => {
      setTimeout(() => {
        if (!data.isInputFocused) {
          data.focusElementStyle = null;
        }
      }, 300);
      data.isInputFocused = false;
    };
    onMounted(() => {
      // DOM 元素将在初始渲染后分配给 ref
      cardNumberRef.value.focus(); // 光标定位
    });
    return {
      ...toRefs(data),
      minCardMonth,
      flipCard,
      focusInput,
      blurInput,
      cardNumberRef,
      cardNameRef,
      cardDateRef,
    };
  },
});
app.mount("#app");
